﻿using UnityEngine;
using Core;
using System.Collections;

#if UNITY_EDITOR
using UnityEditor;
#endif

namespace Core
{
    [DisallowMultipleComponent]
    internal partial class GameInit : BaseInit
    {
        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
        private static void InitGameRuntime()
        {
            InitGame();
        }

        partial void InitGameEditor();

        private static void InitGame()
        {
            Application.runInBackground = true;

            var game = new GameObject("GAME");
            game.AddComponent<GameInit>();
            DontDestroyOnLoad(game);

            Management.Dispose();
            Management.World.AddFeature<FrameFeature>();
        }

        private void Start()
        {
            InitGameEditor();

            var initScene = GameObject.FindObjectOfType<BaseScene>();
            if (initScene != null)
                initScene._OnInit(null);
        }

        private void Update()
        {
            Management.World.Tick();
        }

        private void FixedUpdate()
        {
            Management.World.TickFix();
        }

#if UNITY_EDITOR

        partial void InitGameEditor()
        {
            EditorApplication.pauseStateChanged += EditorApplication_pauseStateChanged;
        }

        private void EditorApplication_pauseStateChanged(PauseState obj)
        {
            if (!Application.isPlaying)
                return;

            switch(obj)
            {
                case PauseState.Paused:
                    new StopTimeClock().Publish();
                    break;
                case PauseState.Unpaused:
                    new StartTimeClock().Publish();
                    break;
            }
        }
#endif
    }
}


